package com.yx.customized;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;

/**
 * Created by yx on 2017/6/2.
 * 等待框，加载中loading...
 * 不能使用Application全局Context,Dialog不支持
 * 如：DialogWaitingUtil.showLoading(MyApplication.getInstance())崩溃！
 * 需传当前上下文，注意及时关闭
 */
public class DialogWaitingUtil {

    private static Dialog dialog;

    public static void showLoading(Context context) {
        View v = LayoutInflater.from(context).inflate(
                R.layout.dialog_waiting_loading, null);
        ProgressBar pb;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            pb = (ProgressBar) v.findViewById(R.id.loading_60);
        } else {
            pb = (ProgressBar) v.findViewById(R.id.loading);
        }
        pb.setVisibility(View.VISIBLE);
        dialog = new AlertDialog.Builder(context, R.style.TranslucentNoBar).show();
        dialog.setOnKeyListener(xxx);
        // 触摸dialog外边时dialog是否消失
        dialog.setCanceledOnTouchOutside(false);
        dialog.setContentView(v);

        Window w = dialog.getWindow();
        WindowManager.LayoutParams lp = w.getAttributes();
        DisplayMetrics d = context.getResources().getDisplayMetrics(); // 获取屏幕宽、高用
        lp.width = (int) (d.widthPixels * 0.28); // 宽度设置为屏幕宽度的0.6--,全宽为1，最低是0
        //lp.height = (int) (d.heightPixels * 0.28); // 高度设置为屏幕的0.6
        lp.height = (int) (d.widthPixels * 0.28); // 高度设置为屏幕宽度的0.6
        // popupWindow.setWidth(display.widthPixels * 9 / 10);
        // popupWindow.setHeight(display.heightPixels * 9 / 10);
        // lp.alpha = 0.3f;
        w.setAttributes(lp);
    }

    public static void hidn() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            dialog.cancel();
            dialog = null;
        }
    }

    private static DialogInterface.OnKeyListener xxx = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {// 按返回键对话框消失，透明度恢复
                    Log.e("aaaa", "---点击了手机返回键---");
                    dialog.dismiss();
                    // WindowManager.LayoutParams lp =
                    // getWindow().getAttributes();
                    // lp.alpha = 1;
                    // getWindow().setAttributes(lp);
                }
            }
            return false;
        }
    };

}
